package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.sky.constant.WeChatLoginConstant.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;


    /**
     * 用户登录功能
     * @param userLoginDTO
     */
    public User login(UserLoginDTO userLoginDTO) {
        //1. 获取OpenId
        String openID = getOpenId(userLoginDTO);
        if (openID==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2. 根据openid查询用户是否存在
        User user = userMapper.getByOpenId(openID);
        if (user==null){
            //2.1 用户不存在，注册一条用户数据
            user = new User();
            //创建时间
            user.setCreateTime(LocalDateTime.now());
            //openId
            user.setOpenid(openID);
            userMapper.insert(user);
        }

        //3. 返回数据
        return user;
    }

    /**
     * 获取OpenId
     * @param userLoginDTO
     * @return
     */
    private String getOpenId(UserLoginDTO userLoginDTO){
        //1. 构建客户端请求
        String code = userLoginDTO.getCode();
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put(JS_CODE_KEY,code);  //js_code
        paramMap.put(APPID_KEY,weChatProperties.getAppid());  //appid
        paramMap.put(SECRET_KEY,weChatProperties.getSecret());  //secret
        paramMap.put(GRANT_TYPE_KEY,AUTHORIZATION_CODE_KEY);  //grant_type
        //2. 向微信服务器发送请求
        String response = HttpClientUtil.doGet(REQUEST_URL_KEY, paramMap);
        JSONObject responseJson = JSONObject.parseObject(response);
        return responseJson.getString(OPEN_ID_KEY);
    }
}
